package cac.gkinterface.service;

import cac.common.CallInterFace.service.CallInterfaceService;
import cac.common.CreatMsgId;
import cac.fenjian.resource.dispatchSearch.dao.MsDeliveryPackageInfoDao;
import cac.fenjian.resource.wmsdeliverplan.dao.WmsDeliverPlanDao;
import cac.gkinterface.dao.ReCallWzDao;
import com.alibaba.fastjson.JSONObject;
import com.cac.dme.adapter.rest.msg.ResponseMsg;
import com.cac.dme.adapter.utils.ComUtil;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;

import org.springframework.core.env.Environment;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@Slf4j
public class ReCallWzService {
    @Autowired
    private Environment environment;
    @Autowired
    private ReCallWzDao testCallWzDao;
    @Autowired
    private WmsDeliverPlanDao wmsDeliverPlanDao;
    @Autowired
    private WorkService workService;
    @Autowired
    private MsDeliveryPackageInfoDao msDeliveryPackageInfoDao;
    @Autowired
    private CallInterfaceService callInterfaceService;


    public ResponseMsg getBData(HashMap para,HashMap issuedTest){
        HashMap map = new HashMap();
        JSONObject headersMap = new JSONObject();
        HashMap data = testCallWzDao.queryWmsDeliveryBarcodeById(para);
        issuedTest.put("id", ComUtil.getId());
        try{
            String requireShop = workService.selectShopByWdpId(para);
            if ("ERP-101-preConfirmCp".equals(data.get("func"))) {
                headersMap.put("func", environment.getProperty("doReturnErp.doCpDeliveryReturnErp.func"));
                map.put("barcode",data.get("barcode"));
                map.put("userCode", data.get("deliveryEmpCode"));
                map.put("userIp", data.get("ip"));
                map.put("opUserCode", data.get("opUserCode"));
                String inventoryCode = environment.getProperty("doReturnErp.doLjDeliveryReturnErp.inventoryCode");
                if("143".equals(requireShop)){
                    inventoryCode += "143";
                }
                map.put("inventoryCode", inventoryCode);
                map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doCpDeliveryReturnErp.wlLogisticsCode"));
            } else if("ERP-101-preConfirmLj".equals(data.get("func"))){
                headersMap.put("func", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.func"));
                map.put("barcode",data.get("barcode"));
                map.put("userCode", data.get("deliveryEmpCode"));
                map.put("userIp", data.get("ip"));
                map.put("opUserCode", data.get("opUserCode"));
                String inventoryCode = environment.getProperty("doReturnErp.doLjDeliveryReturnErp.inventoryCode");
                if("143".equals(requireShop)){
                    inventoryCode += "143";
                }
                map.put("inventoryCode", inventoryCode);
                map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.wlLogisticsCode"));
            }else{
                headersMap.put("func", environment.getProperty("doReturnErp.doBzjDeliveryReturnErp.func"));
                map.put("barcode", data.get("barcode"));
                map.put("userCode", data.get("deliveryEmpCode"));
                map.put("userIp", data.get("ip"));
                map.put("opUserCode", data.get("opUserCode"));
                String inventoryCode = environment.getProperty("doReturnErp.doLjDeliveryReturnErp.inventoryCode");
                if("143".equals(requireShop)){
                    inventoryCode += "143";
                }
                map.put("inventoryCode", inventoryCode);
                map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.wlLogisticsCode"));
            }
            if(map.containsKey("userCode")&&("".equals(map.get("userCode"))||map.get("userCode")==null)){
                return new ResponseMsg().setRetCode("201").setResponseBody("条码号:"+data.get("barcode")+"的移交人工号为空，请完善");
            }
            String mesCheckQualiticationId = (String)data.get("mesCheckQualiticationId");
            //判断条码类型
            if (data.get("erpDeliveryType").toString().contains("CP")) {
                if(mesCheckQualiticationId!=null&&mesCheckQualiticationId.contains("CP")){
                    map.put("barcodeType", "CPHGZ");
                }else{
                    map.put("barcodeType", "BARCODE");
                }
            } else if(data.get("erpDeliveryType").toString().contains("LJ")){
                if(mesCheckQualiticationId!=null&&mesCheckQualiticationId.contains("CP")){
                    map.put("barcodeType", "CPHGZ");
                }else{
                    map.put("barcodeType", "BARCODE");
                }
            } else{
                map.put("barcodeType", "BZJCK");
            }

            log.info(">>>>>>>>>>>>>>>>>>>>>>>map:" + map);
            JSONObject data1 = new JSONObject(map);
            headersMap.put("data", data1);
            String msgId= CreatMsgId.getMsgId();
            headersMap.put("msgId", msgId);
            log.info("data: " + data1.toJSONString());
            String headersmap = headersMap.toJSONString();
            log.info("==========================工控网上传_扫码移交============================");
            //工控网上传数据
            issuedTest.put("BData", headersmap);
            issuedTest.put("type", headersMap.get("func"));
            issuedTest.put("remark","recall");
            issuedTest.put("msgId",msgId);
            log.info("工控网上传程序后台日志:>>>>>>>>>>>>>>>>>issuedParameters:" + issuedTest.toString());
            log.info("==========================工控网上传_扫码移交============================");
            //对已经转换成字符串的数据进行加密
            final Base64.Encoder encoder = Base64.getEncoder();
            String BData = encoder.encodeToString(headersmap.getBytes());
            return new ResponseMsg().setRetCode("200").setResponseBody(BData);
        }catch (Exception e){
            e.printStackTrace();
            String rstl = ExceptionUtils.getFullStackTrace(e);
            rstl = rstl.substring(0,3900);
            return new ResponseMsg().setRetCode("201").setResponseBody(rstl);
        }

    }

    //xiaojian 重推扫码退回的数据
    public String getscanBackBData(HashMap para,HashMap issuedTest){
        JSONObject headersMap = new JSONObject();
        HashMap scanCallBack = testCallWzDao.scanCallBack(para);
        String func = (String) scanCallBack.get("func");
        String barcode = (String) scanCallBack.get("barcode");
        String userCode = (String) scanCallBack.get("userCode");
        String opUserCode = (String) scanCallBack.get("opUserCode");
        String userIp = (String) scanCallBack.get("userIp");
        HashMap map = new HashMap();
        //判断条码类型
        if (func.equals("ERP-101-preConfirmCp")) {
            headersMap.put("func", environment.getProperty("doReturnErp.scanBackCp.func"));
        } else {
            headersMap.put("func", environment.getProperty("doReturnErp.scanBackLj.func"));
        }
        //判断条码类型
        if (barcode.contains("CP-")) {
            map.put("barcodeType", "CPHGZ");
        } else map.put("barcodeType", "BARCODE");
        map.put("userCode", userCode);
        map.put("opUserCode", opUserCode);
        map.put("userIp", userIp);
        map.put("barcode",barcode);
        JSONObject data = new JSONObject(map);

        //放入请求头
        headersMap.put("data", data);
        String msgId= CreatMsgId.getMsgId();
        headersMap.put("msgId", msgId);
        String headersmap = headersMap.toJSONString();
        //工控网上传数据
        issuedTest.put("BData", headersmap);
        issuedTest.put("type", headersMap.get("func"));
        issuedTest.put("remark","recall");
        issuedTest.put("msgId",msgId);
        Base64.Encoder encoder = Base64.getEncoder();
        String BData = encoder.encodeToString(headersmap.getBytes());
        log.info("重传扫码退回参数：",BData);
        return BData;
    }
    //xiaojian 重推协调单管理数据
    public String getCoordinateBData(HashMap para,HashMap issuedTest){
        JSONObject headersMap = new JSONObject();
        //获得需要重推协调单数据
        HashMap coordinateRecall = testCallWzDao.sendCoordinateRecall(para);
        JSONObject data = new JSONObject(coordinateRecall);
        headersMap.put("func", environment.getProperty("deliveryCoordinate.func"));
        //放入请求头
        headersMap.put("data", data);
        String msgId= CreatMsgId.getMsgId();
        headersMap.put("msgId", msgId);
        String headersmap = headersMap.toJSONString();
        //工控网上传数据
        issuedTest.put("BData", headersmap);
        issuedTest.put("type", headersMap.get("func"));
        issuedTest.put("remark","recall");
        issuedTest.put("msgId",msgId);
        Base64.Encoder encoder = Base64.getEncoder();
        String BData = encoder.encodeToString(headersmap.getBytes());
        log.info("重推协调单参数：",BData);
        return BData;
    }

    public String scanDelivery(String barcode,String msgId, String barcodeType, String bzjCodeType,String wmsDeliveryPlanId) {
        HashMap map = new HashMap();
        JSONObject headersMap = new JSONObject();
        HashMap para = new HashMap();
        para.put("wmsDeliveryPlanId",wmsDeliveryPlanId);
        HashMap ba = testCallWzDao.queryWmsDeliveryBarcodeById(para);
        String func = ba.get("func").toString();
        String userCode = ba.get("deliveryEmpCode").toString();
        String userIp = ba.get("ip").toString();
        String opUserCode = ba.get("opUserCode").toString();
        if (func.equals("ERP-101-preConfirmCp")) {
            headersMap.put("func", environment.getProperty("doReturnErp.doCpDeliveryReturnErp.func"));
            map = wmsDeliverPlanDao.scanDeliveryCp(barcode);
            map.put("userCode", userCode);
            map.put("userIp", userIp);
            map.put("opUserCode", opUserCode);
            map.put("inventoryCode", environment.getProperty("doReturnErp.doCpDeliveryReturnErp.inventoryCode"));
            map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doCpDeliveryReturnErp.wlLogisticsCode"));
        } else if (func.equals("ERP-101-preConfirmLj")) {
            headersMap.put("func", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.func"));
            map = wmsDeliverPlanDao.scanDeliveryLj(barcode);
            map.put("userCode", userCode);
            map.put("userIp", userIp);
            map.put("opUserCode", opUserCode);
            map.put("inventoryCode", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.inventoryCode"));
            map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.wlLogisticsCode"));
        } else {//yebo 新增标件
            headersMap.put("func", environment.getProperty("doReturnErp.doBzjDeliveryReturnErp.func"));
            map.put("barcode", barcode);
            map.put("userCode", userCode);
            map.put("userIp", userIp);
            map.put("opUserCode", opUserCode);
            map.put("inventoryCode", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.inventoryCode"));
            map.put("wlLogisticsCode", environment.getProperty("doReturnErp.doLjDeliveryReturnErp.wlLogisticsCode"));
        }
        //判断条码类型
        if (barcodeType.equals("LJ")) {
            map.put("barcodeType", "BARCODE");
        } else if (barcodeType.equals("CP")) {
            map.put("barcodeType", "CPHGZ");
        } else {
            map.put("barcodeType", bzjCodeType);
        }

        headersMap.put("msgId", msgId);
        JSONObject data = new JSONObject(map);
        headersMap.put("data", data);
        String headersmap = headersMap.toJSONString();

        //工控网上传数据
        HashMap issuedTest = new HashMap();
        issuedTest.put("BData", headersmap);
        issuedTest.put("msgId", msgId);
        issuedTest.put("type", headersMap.get("func"));
        issuedTest.put("remark", "recall");
        workService.issuedTest(issuedTest);
        log.info("==========================工控网上传_扫码移交=重推===========================");
        log.info(headersMap.toJSONString());
        //对已经转换成字符串的数据进行加密
        final Base64.Encoder encoder = Base64.getEncoder();
        String BData = encoder.encodeToString(headersmap.getBytes());
        return BData;
    }

    public HashMap makeMaterialCheck() {

        List<String> allotmentIdArray = testCallWzDao.queryInvOutAllotmentIds();
        for(String allotmentId : allotmentIdArray){
            String msgId = CreatMsgId.getMsgId();
            //查询此占用数据的合格证号
            String hgzNo = msDeliveryPackageInfoDao.queryHgzNo(allotmentId);
            HashMap invOut = new HashMap();
            invOut.put("wmsInvOutAllotmentId", allotmentId);
            invOut.put("opUserCode", "488831");
            invOut.put("userIp", "173.53.29.67");
            if(hgzNo==null){
                invOut.put("hgzNo","");
            }else{
                invOut.put("hgzNo",hgzNo);
            }
            //判断是否有流水 无流水则记录流水 2023-11-1
            int ct = msDeliveryPackageInfoDao.queryIsExistsTransaction(invOut);
            if(ct==0){//无流水
                //查询修改流水需要的数据
                HashMap itemInv = msDeliveryPackageInfoDao.searchInventory(invOut);
                itemInv.put("wmsInvOutAllotmentId",allotmentId);
                itemInv.put("logId","recallTabSend");
                //配送之后修改流水表数据
                msDeliveryPackageInfoDao.insertTransaction(itemInv,hgzNo);
            }

            JSONObject funcJson = new JSONObject(invOut);
            JSONObject resultOb = new JSONObject();
            resultOb.put("data", funcJson);
            resultOb.put("func", environment.getProperty("dispatch.sortingInvOut"));
            resultOb.put("msgId", msgId);
            //业务数据加密
            final Base64.Encoder encoder = Base64.getEncoder();
            String parameters = encoder.encodeToString(resultOb.toJSONString().getBytes());
            log.info("============================工控网上传_分拣出库==========================");
            String code = "sendBData";
            String sendScenario = "分拣出库";
            String name = "两网传输-发送业务数据";
            long beginTime = System.currentTimeMillis();
            log.info("======开始时间=======" + beginTime);
            HashMap rsl1 = callInterfaceService.sendBData(code, name, parameters, sendScenario);
            long endTime = System.currentTimeMillis();
            log.info("======消耗时间=======" + (endTime - beginTime) + "ms");
            log.info("============================工控网上传_分拣出库==========================");
            //工控网上传数据
            HashMap issuedTest = new HashMap();
            issuedTest.put("businessTab","wms_inv_out_allotment");
            issuedTest.put("businessCol","wms_inv_out_allotment_id");
            issuedTest.put("businessVal",allotmentId);
            issuedTest.put("BData", resultOb.toJSONString());
            issuedTest.put("type", resultOb.get("func"));
            issuedTest.put("msgId", msgId);
            issuedTest.put("remark", "recall");
            workService.issuedTest(issuedTest);
            log.info("工控网上传程序后台日志:>>>>>>>>>>>>>>>>>>>>>>>>>issuedParameters:" + issuedTest.toString());
            testCallWzDao.updateMsRecallTabStatusByAllotmentId(allotmentId);
        }
        log.info("==================批量推送ERP出库完成============");
        return null;
    }



    public void sendSortOccupy(){
        String IP = "173.53.29.67";
        String opUserCode="488831";
        List<HashMap> list = testCallWzDao.queryOccupyInfo();
        for(HashMap hashMap : list){
            String allotmentId = (String) hashMap.get("originalId");
            //分拣占用，调用回传ERP
            String parameters = this.sortOccupy(opUserCode, IP, hashMap);
            String code = "sendBData";
            String sendScenario = "分拣占用";
            String name = "两网传输-发送业务数据";
            long beginTime = System.currentTimeMillis();
            log.info("======开始时间=======" + beginTime);
            callInterfaceService.sendBData(code, name, parameters, sendScenario);
            log.info("==========执行业务数据处理===========");
            long endTime = System.currentTimeMillis();
            log.info("======消耗时间=======" + (endTime - beginTime) + "ms");
            testCallWzDao.updateMsRecallTabStatusByAllotmentId(allotmentId);
        }

    }

    public String sortOccupy(String opUserCode, String IP, HashMap map) {
        JSONObject headersMap = new JSONObject();
        String msgId = CreatMsgId.getMsgId();
        //获取func
        headersMap.put("func", environment.getProperty("doReturnErp.sortOccupy.func"));
        headersMap.put("msgId", msgId);
        //分拣占用接口所需参数
        map.put("opUserCode", opUserCode);
        map.put("userIp", IP);
        map.put("taskNo", "");
        map.put("recHrDeptId", "");

        JSONObject data = new JSONObject(map);
        headersMap.put("data", data);
        String headersmap = headersMap.toJSONString();
        log.info("分拣占用上传ERP===============" + headersmap);
        //对已经转换成字符串的数据进行加密
        final Base64.Encoder encoder = Base64.getEncoder();
        String BData = encoder.encodeToString(headersmap.getBytes());
        log.info("==========================工控网上传_分拣占用============================");
        //工控网上传数据
        HashMap issuedTest = new HashMap();//originalId
        issuedTest.put("businessTab","wms_inv_out_allotment");
        issuedTest.put("businessCol","wms_inv_out_allotment_id");
        issuedTest.put("businessVal",map.get("originalId"));
        issuedTest.put("BData", headersmap);
        issuedTest.put("msgId", msgId);
        issuedTest.put("type", headersMap.get("func"));
        issuedTest.put("remark", "recall");
        log.info("工控网上传程序后台日志:>>>>>>>>>>>>>>>>>>>>>>>>>issuedParameters:" + issuedTest.toString());
        log.info("==========================工控网上传_分拣占用============================");
        workService.issuedTest(issuedTest);
        return BData;
    }

}
